<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>ECharts</title>
  <!-- 引入刚刚下载的 ECharts 文件 -->
  <script src="./js/echarts.min.js"></script>
  <script src="./js/topic.js"></script>
  <style>
    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
#ah{
    padding: 20px;
    background-color: #36648B;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.6);
}
#ah img{
    float: right;
    width: 85px;
    height: 85px;
    object-fit:cover;
    border: 1px solid #7A8B8B;
    border-radius: 10px 10px 10px 10px;
    margin-left: 10px;
    margin-top: 0px;
    cursor: pointer;
}
#ah p{
    display: inline-block;
    font-size: 35px;
    color: white;
}
.Table{
    display: flex;
    border-radius: 15px;
    justify-content: center;
    align-items: center;
    font: 900 40px '';
    text-align: center;
    letter-spacing: 5px;
}
.box1{
    width: 80%;
    /* 居中 */
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 5px;
     /* 文字位置居中 */
    text-align: center;
}
.container {
    display: flex;
    justify-content: space-between;
    flex-direction: column; /*上下分离*/
    /* margin: 20px 0; */
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0,0,0.6);
    background-color: #FFFFFF;
    /* 一行有四个 */
    flex: 1 1 calc(25% - 20px);
    height: 70px;
   margin-bottom: 20px;
   padding: 5px;
    }
.lable{
    display: block;
    font-size: 14px;
    color: #36648B;
    font-weight: 700;
    /* 高度位置在这一行的中间 */
    line-height: 80px;
}
.containerH{
    margin-top: 5px;
    font-size: 12px;
    flex: 1;
    align-self: flex-start; /* 左对齐 */
}
.contanerSpacer{
    height: 2px;
}
.containerIn{
    /* 文字内容居中，高度居中，边框凹陷 */
    display: flex;
    justify-content: center;    
    align-items: center;    
    width: 100%;
    /* border-radius: 8px;  */
    margin: 0 auto;
    border: 2px inset #ccc;  
    flex: 4;
}
    .curve {
    margin-top: 20px;
    }
    #return {
        /* 使按钮的位置始终在页面的左下角，大小适中 */
        position: fixed;
        bottom: 20px;
        left: 20px;
        width: 100px;
        height: 50px;
        color: #fff;
        background-color: #36648B;
        cursor: pointer;
        box-shadow: 0 0 10px #36648B;
        border-radius: 5px;
        font-size: 18px;
    }
    #return:hover {
        font-weight: bold;
        cursor: pointer;
        color: #36648B;;
        background-color: #fff;
    }
    .chartContainer{
      display: flex;
      justify-content: space-between; /*子元素之间空间均匀分布 */
      /* 底部50px */
      margin-bottom: 50px;
    }
    .chart{
      width: 33.3%;
      height: 400px;
      /* margin: 5px; */
    }
  </style>
</head>
<body>
  <div id="ah">
    <img
    src="https://image0.lietou-static.com/bg_white_192x192/6371d7aa64ae7150b5a9edad05u.png"
    alt="this is a img"
    />
    <p class="Table">安时商用储能</p>
  </div>
<!-- 在页面的左下角创建一个大小合适的按钮 -->
  <div class="button">
    <button id="return" onclick="funReturn()">注销</button>
  </div>
<h3>设备一</h3>
  <div class="box1" id="settings-01">
    <span class="lable">Name</span>
    <div class="container">
        <h4 class="containerH">最新电压</h4>
        <div class="contanerSpacer"></div>
        <div class="containerIn" id="name1"></div>
  </div>
  <span class="lable">Value</span>
    <div class="container">
        <h4 class="containerH">最新电流</h4>
        <div class="contanerSpacer"></div>
        <div class="containerIn" id="value1"></div>
    </div>
</div>

<h3>设备二</h3>
<div class="box1" id="settings-02">
    <span class="lable">Name</span>
    <div class="container">
        <h4 class="containerH">最新电压</h4>
        <div class="contanerSpacer"></div>
        <div class="containerIn" id="name2"></div>
    </div>
   
  <span class="lable">Value</span>
    <div class="container">
        <h4 class="containerH">最新电流</h4>
        <div class="contanerSpacer"></div>
        <div class="containerIn" id="value2"></div>
    </div>
</div>

<h3>设备三</h3>
<div class="box1" id="settings-03">
    <span class="lable">Name</span>
    <div class="container">
        <h4 class="containerH">最新电压</h4>
        <div class="contanerSpacer"></div>
        <div class="containerIn" id="name3"></div>
    </div>
   
    <span class="lable">Value</span>
    <div class="container">
        <h4 class="containerH">最新电流</h4>
        <div class="contanerSpacer"></div>
        <div class="containerIn" id="value3"></div>
    </div>
</div>
<div class="chartContainer">
   <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
   <div id="device01" class="chart"></div>
   <div id="device02" class="chart"></div>
   <div id="device03" class="chart"></div>
</div>
 
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
<script type="text/javascript">

// 全局变量，用来记录当前选中的设备(根据设备号)
var currentDevice = "";
// 使用JavaScript读取data.json中的数据，并填充到对应的区域中
function updata(){
    fetch('./static/data.json')
    .then(responses => responses.json())
    .then(data =>{
        // 便利数据
        data.forEach(deviceItem =>{
            // 根据不同设备号分配数据到不同的位置
            if(deviceItem.device == '01'){
                currentDevice = '1';
                updataSetting('settings-01',deviceItem.data,currentDevice);
            }else if(deviceItem.device == '02'){
                currentDevice = '2';  
                updataSetting('settings-02',deviceItem.data,currentDevice);
            }else if(deviceItem.device == '03'){
                currentDevice = '3';
                updataSetting('settings-03',deviceItem.data,currentDevice);
            }
            //...
        });
    })
    .catch(error => console.error('Error fetching data:',error));
}

function updataSetting(settingId,data,deviceNumber){
      // 根据ID获取对应设备的设置容器
      const settingElement = document.getElementById(settingId);

    // 遍历数据，并填充到设置的容器中

    // 因为forEach是异步执行的，而全局变量currentDevice在updata函数中是被不同设备循环赋值的，因此当updataSetting函数实际执行时，currentDevice已经被更新为最后一个设备的值，解决这个问题可以将currentDevice作为参数传递给updataSetting,确保在函数内部使用正确的设备值

    data.forEach(item =>{
        // 将item.name填入到id=name + currentDevice的区域
        document.getElementById(`name${deviceNumber}`).innerHTML = item.name;
        // 将item.value填入到id=value + currentDevice的区域
        document.getElementById(`value${deviceNumber}`).innerHTML = item.value;
    });
}
// 每秒定时刷新数据
setInterval(updata,1000);
function funReturn(){
      window.location.href = "./";
  }

    // 初始化 ECharts 实例
    var myChart01 = echarts.init(document.getElementById('device01'),'topic');
    var myChart02 = echarts.init(document.getElementById('device02'),'topic');
    var myChart03 = echarts.init(document.getElementById('device03'),'topic');

    // 储存每个设备的数据
    var device01Data = [],
        device02Data = [],
        device03Data = [];

    async function fetchData() {
      try {
        // 使用ajax获取data.json中的数据，这里使用fetch作为示例
        let response = await fetch('./static/data.json');
        let allData = await response.json();

        // 更新每个设备的数据
        updataDataForDevice(allData,'01',myChart01,device01Data,'设备一的图表');
        updataDataForDevice(allData,'02',myChart02,device02Data,'设备二的图表');
        updataDataForDevice(allData,'03',myChart03,device03Data,'设备三的图表');
      }catch (error) {
        console.log('Error fetching data:',error);
      }
    }

    function updataDataForDevice(allData,deviceId,Chart,dataStore,titleText){
      // 获取当前设备的数据
      let deviceData = allData.find(item => item.device === deviceId);
      // 更新数据
      dataStore.push({
        time: new Date().toLocaleTimeString(), // 使用当前时间作为X轴的值
        Name: deviceData.data.map(item => parseFloat(item.name)), // name数据
        Value: deviceData.data.map(item => parseFloat(item.value)), //value数据
    });
        // 控制图表只展示最近的一定数量的数据
        if (dataStore.length > 5) {
          dataStore.shift(); // 移除最旧的数据
        }

        // 更新图表
        Chart.setOption({
          title: {						//配置标题
          text: titleText,
          // left:'center'   //标题居中
        },
        tooltip: {},		//配置提示框
        legend: {						//配置图例
          data: ['电压', '电流']
        },
          xAxis: {
            type: 'category',
            data: dataStore.map(function(item) {
              return item.time; // 使用时间戳作为X轴的值
            })
          },
          yAxis: {
              type: 'value',
              name: '数值(V/A)',
              min: 0,
              max: 2,
              axisLabel: {
                formatter: '{value}'
              }
            },
          series: [
            {
              name: '电压',
              type: 'line',
              data: dataStore.flatMap(function(item) {
                return item.Name;
              })
            },
            {
              name: '电流',
              type: 'line',
              data: dataStore.flatMap(function(item) {
                return item.Value;
              })
            }
          ]
        });
      }

    setInterval(fetchData, 1000); // 每秒更新一次a
  </script>
</html>